﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Quartz;
using ServiceJob;
using Quartz.Impl;
using System.Data;

namespace QuartzScheduler.ExpandClass
{
    public static class JobManager
    {

        /// <summary>
        /// 添加一个工作并启动
        /// </summary>
        /// <param name="JobClassName">工作的类名</param>
        /// <param name="JobName">工作名</param>
        /// <param name="Cron">Cron表达式</param>
        /// <returns></returns>
        public static bool AddJob(HttpRequestBase Request)
        {
            string JobClassName = GetRequestInfo.getJobClass(Request);
            string JobName = GetRequestInfo.getJobName(Request);
            string Cron = GetRequestInfo.getCron(Request);
            DateTime beginTime = GetRequestInfo.beginDateTime(Request);
            DateTime? endTime = GetRequestInfo.endDateTime(Request);
            Dictionary<string,object> jobInfos = GetRequestInfo.jobInfos(Request);
            TimeSpan triggertime = GetRequestInfo.getTriggerTime(Request);

            // 获取一个任务调度器
            //ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            // 获取一个任务调度器
            //IScheduler scheduler = schedulerFactory.GetScheduler();
            IScheduler scheduler = SchedulerManager.GetScheduler();
            // 创建一个工作
            Type type = JobClassReturn.jobClassReturn(JobClassName);
            JobDetail job = new JobDetail(JobName, JobClassReturn.DEFAULT_GROUP, type);

            // 创建一个触发器
            try
            {
                string sql = "";
                DateTime endDateTime;
                if (endTime != null)
                {
                    endDateTime = (DateTime)endTime;
                    sql = string.Format(@" insert into T_RunJob (jobID,jobName,beginDateTime,endDateTime,descriptionInfo,cronExpression,triggertime) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", jobInfos["jobID"].ToString(), JobName, beginTime.ToLocalTime(),
                                  endDateTime.ToLocalTime(), jobInfos["descriptionInfo"], Cron,triggertime);
                }
                else
                {
                    sql = string.Format(@" insert into T_RunJob (jobID,jobName,beginDateTime,descriptionInfo,cronExpression,triggertime) values ('{0}','{1}','{2}','{3}','{4}','{5}')", jobInfos["jobID"].ToString(), JobName, beginTime.ToLocalTime(),
                                                      jobInfos["descriptionInfo"], Cron,triggertime);
                }
                SqlServerClass ssc = new SqlServerClass();
                ssc.MySqlExcute(sql);
                CronTrigger trigger = new CronTrigger();
                trigger.Name = Guid.NewGuid().ToString();
                trigger.JobName = JobName;
                trigger.JobGroup = JobClassReturn.DEFAULT_GROUP;
                trigger.Group = JobClassReturn.DEFAULT_Trigger_GROUP;
                trigger.CronExpression = new CronExpression(Cron);
                trigger.StartTimeUtc = beginTime;
                trigger.EndTimeUtc = endTime;
                scheduler.AddJob(job, true);

                if (endTime != null)
                {
                    doDelete(scheduler, (DateTime)endTime);
                }
                DateTime ft = scheduler.ScheduleJob(trigger);
            }
            catch 
            {
                return false;
            }
            
            if (!scheduler.IsStarted)
            {
                scheduler.Start();
            }
            return true;
        }

        private static void doDelete(IScheduler scheduler,DateTime time)
        {
            string JobName1 = "delete" + Guid.NewGuid().ToString();
            Type type1 = JobClassReturn.jobClassReturn("IJobDeleteExpired");
            JobDetail job1 = new JobDetail(JobName1, JobClassReturn.DEFAULT_GROUP, type1);
            SimpleTrigger trigger1 = new SimpleTrigger();
            trigger1.Name = Guid.NewGuid().ToString();
            trigger1.JobName = JobName1;
            trigger1.JobGroup = JobClassReturn.DEFAULT_GROUP;
            trigger1.Group = JobClassReturn.DEFAULT_Trigger_GROUP;
            //trigger.CronExpression = new CronExpression(Cron);
            trigger1.RepeatInterval = new TimeSpan(0, 0, 1);
            trigger1.RepeatCount = 1;
            trigger1.StartTimeUtc = time.ToUniversalTime();
            trigger1.EndTimeUtc = null;
            scheduler.AddJob(job1, true);
            DateTime ft1 = scheduler.ScheduleJob(trigger1);
        }
    }
}